﻿using Inovout.Services;
using NHibernate.Criterion;
using System;
using System.Security.Cryptography;
using System.Text;

namespace Inovout.Security.Services
{
    public class FormsUserService : RepositoryService<FormsUser>, IFormsUserService
    {
        //public bool Authenticate(string userName, string password)
        //{
        //    FormsUser user = base.Repository.Find(Restrictions.Eq("Name", userName).IgnoreCase());
        //    if (user == null)
        //    {
        //        return false;
        //    }

        //    return user.Password.Equals(Encrypt(password, user.PasswordSalt));
        //}

        public FormsUser FindByName(string Name) 
        {
            return base.Repository.Find(Restrictions.Eq("Name", Name).IgnoreCase());
        }

        public override void Save(FormsUser entity)
        {
            if (string.IsNullOrEmpty(entity.PasswordSalt))
            {
                entity.PasswordSalt = GenerateSalt();
            }
            entity.Password = Encrypt(entity.Password, entity.PasswordSalt);
            base.Save(entity);
        }
        public void Create(IFormsUser user)
        {
            Save((FormsUser)user);
        }

        private string Encrypt(string password, string salt)
        {
            HMACMD5 hmacmd5 = new HMACMD5(Convert.FromBase64String(salt));
            return Convert.ToBase64String(hmacmd5.ComputeHash(Encoding.Unicode.GetBytes(password)));
        }
        private string GenerateSalt()
        {
            byte[] buffer = new byte[0x10];
            new RNGCryptoServiceProvider().GetBytes(buffer);
            return Convert.ToBase64String(buffer);
        }



    }
}
